package com.jd.cs.config.interceptor;

import com.jd.cs.common.ApiUtil;
import com.jd.cs.common.Const;
import com.jd.cs.common.MD5Util;
import com.jd.cs.error.ErrorCode;
import com.jd.cs.exception.APIException;
import com.jd.cs.service.MemTokenService;
import com.jd.cs.vo.TokenInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: lizhiwei
 * @date: 2020-07-25 20:23
 **/
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter {
    private final static Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    @Resource
    MemTokenService memTokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        logger.info("request:{}", request);
        return checkToken(request);
    }

    private boolean checkToken(HttpServletRequest request) {
        String token = request.getHeader(Const.Header.TOKEN);
        if (StringUtils.isEmpty(token)) {
            throw new APIException(ErrorCode.E_20000);
        }
        String timestamp = request.getHeader(Const.Header.TIMESTAMP);
        if (StringUtils.isEmpty(timestamp)) {
            return false;
        }
        String nonce = request.getHeader(Const.Header.NONCE);
        if (StringUtils.isEmpty(nonce)) {
            return false;
        }
        String sign = request.getHeader(Const.Header.SIGN);
        if (StringUtils.isEmpty(sign)) {
            return false;
        }

        TokenInfo tokenInfo = memTokenService.get(token);
        if (tokenInfo == null) {
            return false;
        }
        // 4. 校验签名(将所有的参数加进来，防止别人篡改参数) 所有参数看参数名升续排序拼接成url
        // 请求参数 + token + timestamp + nonce
        String signString = ApiUtil.concatSignString(request) + tokenInfo.getAppInfo().getKey() + token + timestamp + nonce;
        String signature = MD5Util.encode(signString);

        return signature.equals(sign);
    }

}